<template>
	<view>
		<view class="page">
			<l-file ref="lFile" @up-success="onSuccess"></l-file>
			<uni-card>
				<mpopupHeaderRadioItem label="核查人员姓名" :custom-class="'custom-align'"
					:custom-style="{ padding: '20rpx' }">
					<input class="centered-input" v-model="orderList.checkStaffName" placeholder="请输入核查人员" />
				</mpopupHeaderRadioItem>

				<mpopupHeaderRadioItem label="核查日期" height="90px" :custom-class="'custom-align'"
					:custom-style="{ padding: '20rpx' }">
					<view class="example-body">
						<uni-datetime-picker @change="handleDateRangeChange" v-model="dataChange" type="daterange"
							@maskClick="maskClick" rangeSeparator="至" />
					</view>
				</mpopupHeaderRadioItem>
				<mpopupHeaderRadioItem label="核查单位名称" :custom-class="'custom-align'"
					:custom-style="{ padding: '20rpx' }">
					<input class="centered-input" v-model="orderList.operatorName" placeholder="请输入单位名称" />
				</mpopupHeaderRadioItem>


				<mpopupHeaderRadioItem label="对核查工作的评价" :custom-class="'custom-align'"
					:custom-style="{ padding: '20rpx' }">
					<!-- 新增包裹容器 -->
					<view class="evaluation-container">
						<view class="evaluation-item" v-for="(item, index) in evaluations" :key="index">
							<view class="question-text">{{ item.question }}</view>
							<uni-data-checkbox v-model="orderList[item.field]"
								:localdata="checkItem"></uni-data-checkbox>
						</view>

						<view>
							<view style="text-align: center;">如核查过程中核查人员有违反廉洁公正纪律的行为,请简要描述核查人员的违规行为：</view>
							<view class="clickable-cell" @tap="onUpload(index)">
								{{ this.orderList.filename ||  '点击编辑/上传附件' }}
							</view>
							<view style="text-align: center;color: #007AFF;">(本处写不下的，可另附书面说明)</view>
						</view>
					</view>



				</mpopupHeaderRadioItem>
				<mpopupHeaderRadioItem label="对核查工作的意见和建议" :custom-class="'custom-align'" :show-bottom-border="true"
					:custom-style="{ padding: '20rpx' }">
					<input class="centered-input" v-model="orderList.remark" placeholder="请输入意见和建议" />
				</mpopupHeaderRadioItem>
			</uni-card>


			<uni-card>
				<view class="dashed-box">
					<view class="container">

						<view class="custom-title">
							<view class="content-wrapper">
								<text class="label-text">单位名称:</text>
								<input v-model="orderList.unitName" class="underline-input" placeholder="请输入单位名称" />
							</view>
						</view>

						<view class="custom-title">
							<view class="content-wrapper">
								<text class="label-text">联系电话:</text>
								<input v-model="orderList.contactNumber" class="underline-input"
									placeholder="请输入联系电话" />
							</view>
						</view>

						<view class="custom-title">
							<view class="content-wrapper">
								<text class="label-text">E-mail:</text>
								<input v-model="orderList.eMail" class="underline-input" placeholder="请输入E-mail" />
							</view>
						</view>

						<view class="custom-title">
							<text class="label-text-sign">法定代表人或负责人签字</text>
							<signInput class="underline-sign" :initialImage="this.orderList.approverPersonSign"
								@signToUrl="signToUrl" />
						</view>

						<!-- 核查人员日期 -->
						<view class="custom-dateText">
							<text @click="openDatePicker()"
								class="custom-text3">{{ this.orderList.approverPersonDate || '选择日期' }}</text>
						</view>


					</view>

					<!-- 其他代码不变 -->
					<stampSection @stamp-click="handleStampClick" />
					<text>{{word_address}}</text>

				</view>

			</uni-card>
			<!-- 添加日期选择弹窗 -->
			<uni-popup ref="datePopup" type="dialog">
				<uni-popup-dialog mode="base" title="选择日期" @confirm="handleDialogConfirm" @close="handleDialogClose">
					<uni-datetime-picker type="date" @change="handleDateChange" />
				</uni-popup-dialog>
			</uni-popup>
		</view>

		<view v-if="editStatus!='FALSE'" class="button-container">
			<view class="button-save">
				<button style="flex: 1;" type="primary" @click="submitForm('1')">保存并提交纪律反馈单</button>
			</view>
			<view class="button-save">
				<button style="flex: 1;" type="primary" @click="submitForm('0')">暂存</button>
			</view>
		</view>
	</view>

</template>

<script>
	import signInput from "@/components/am-sign-input/am-sign-input.vue"
	import mpopupHeaderItem from "@/components/mpopup-header-item.vue"
	import mpopupHeaderRadioItem from "@/components/mpopup-header-radio-item.vue"
	import mpopupTable from "@/components/mpopup-table.vue"
	import stampSection from '@/components/order/stamp-section.vue'
	import {
		foodProductionAdd,
		getMedicalDict,foodProductionUpdate,
		foodProductionInfo
	} from '@/api/order'
	export default {
		components: {
			signInput,
			mpopupHeaderRadioItem,
			mpopupHeaderItem,
			mpopupTable,
			stampSection
		},
		onLoad(options) {
			if (options.editStatus != null) {
				const editStatus = decodeURIComponent(options.editStatus);
				const workOrderId = decodeURIComponent(options.workOrderId);
				this.orderList.workOrderId = workOrderId;
				this.editStatus = editStatus;
				this.getfoodProductionInfo(workOrderId);
			} else {
				if (options.orderData) {
					const orderData = JSON.parse(decodeURIComponent(options.orderData));
					const orderid = decodeURIComponent(options.workOrderId);


					this.orderList.bidType = orderData.bidType;
					this.orderList.orderCategory = orderData.orderCategory;
					this.orderList.operatorName = orderData.operatorName;
					this.orderList.workOrderId = orderid;
				}
			}
			this.getMedicalDict('word_address');
		},
		data() {
			return {
				dataChange:[],
				word_address: '',
				uploadUrl: "https://8954wg323mw0.vicp.fun/app/upload/uploadFile",
				editStatus: 'ADD',
				tempDate: '',
				isStampEnabled: false, // 控制签章区域显示/隐藏
				orderList: {
					workOrderId: '',
					checkStaffName: '', //核查人员名称
					operatorName: '',
					checkStartTime: '',
					checkEndTime: '',
					validWorkPermit: '', // 有效工作证
					violation: '', // 违规行为
					interestBehavior: '', // 不当利益行为
					JustConduct: '', // 公正行为
					violationAttachment: '', //违规附件
					filename: '',
					remark: '',
					unitName: '', //被查单位名称
					contactNumber: '', //联系电话
					approverPersonSign: '', //签字
					eMail: '',
					approverPersonDate: '', //签字日期
					createBy: '', //系统管理员
					auditStatus: '', //暂存给0,提交给1 工单状态 [0：未完成，1：完成]
					bidType: '',
					orderCategory: ''
				},
				evaluations: [{
						question: '1.核查人员核查前，是否出示有效工作证?',
						field: 'validWorkPermit' // 对应orderList中的字段
					},
					{
						question: '2.核查人员在核查过程中是否有吃、拿、卡、要等行为?',
						field: 'violation'
					},
					{
						question: '3.核查人员在核查过程中是否有从事生产许可有偿咨询或推销服务等向被核查单位谋取不正当利益的行为?',
						field: 'interestBehavior'
					},
					{
						question: '4.核查人员在核查过程中是否有其他违反廉洁公正的行为?',
						field: 'JustConduct'
					}
				],
				checkItem: [{
						text: '是',
						value: '0'
					},
					{
						text: '否',
						value: '1'
					}
				],
			}
		},
		methods: {
/**
			 * @param {Object} e
			 * 返回的签名地址 企业负责人签名
			 */
			signToUrl(e) {
				if (e.error_code && e.error_code === '201') {
					uni.showToast({
						title: e.msg,
						icon: 'none'
					})
					return
				}
				const response = JSON.parse(e.data)
				this.orderList.approverPersonSign = response.data;

			},

			// 获取食品生产工单详情
			async getfoodProductionInfo(orderId) {
				const id = {
					workOrderId: orderId
				}
				const res = await foodProductionInfo(id);
				if (res.code === 0) {
					this.orderList = res.data;
// 修改后（正确方式）
					this.dataChange = [
						new Date(this.orderList.checkStartTime).getTime(),
						new Date(this.orderList.checkEndTime).getTime()
					];
				}
			},
			async submitForm(status) {
				try {
					// 状态校验前置
					if (this.editStatus === 'FALSE') {
						return uni.showToast({
							title: '当前处于查看状态',
							icon: 'none'
						});
					}
					// 统一处理提交逻辑
					const isEditMode = this.editStatus === 'EDIT';
					const apiMethod = isEditMode ? foodProductionUpdate : foodProductionAdd;
					// 构造请求参数（避免污染原始数据）
					const payload = {
						...this.orderList,
						auditStatus: status,
					};

					// 显示加载状态
					uni.showLoading({
						title: '提交中...',
						mask: true
					});

					console.log(payload)
					// 执行API调用
					const res = await apiMethod(payload);

					if (res.code !== 0) {
						throw new Error(res.msg || '服务器处理异常');
					}

					// 统一处理成功逻辑
					uni.showToast({
						title: '提交成功',
						icon: 'success'
					});

					// 关闭当前页面，跳转到工单页
					this.$closeAndRedirect({
					  url: '/pages/work/history/index'
					});

				} catch (error) {
					// 统一错误处理
					console.error('提交失败:', error);
					uni.showToast({
						title: error.msg || '请求失败，请检查网络',
						icon: 'none',
						duration: 3000
					});
				} finally {
					uni.hideLoading();
				}
			},


			//获取字典值
			async getMedicalDict(type) {
				try {
					const res = await getMedicalDict(type)
					// 增加响应状态判断
					if (res.code === 0) {
						if (type === 'bid_type') {
							this.valueOptions = res.data.map(item => ({
								text: item.label,
								value: String(item.value) // 确保字典值转为字符串
							}));

						}
					} else {
						throw new Error(res?.data?.msg || '接口返回异常')
					}
				} catch (error) {
					uni.showToast({
						title: error.message || '获取失败',
						icon: 'none',
						duration: 2000
					})
				}
			},

		

			// 修改后的上传方法
			onUpload(index) {
				this.$refs.lFile.upload({
					url: this.uploadUrl,
					name: 'file'
				});
			},
			onSuccess(res) {
			  // 确保数据结构正确（根据实际接口返回调整）
			  const fileName = res.fileName || res.data?.fileName;
			  const filePath = res.data?.data || res.filePath;
			  
			  // 使用Vue.set确保响应式更新
			  this.$set(this.orderList, 'filename', fileName);
			  this.$set(this.orderList, 'violationAttachment', filePath);
			  
			  console.log('上传成功', {
			    filename: this.orderList.filename,
			    attachment: this.orderList.violationAttachment
			  });
			},
			// 处理启用状态变化
			handleEnableChange(status) {
				console.log('签章功能状态:', status)
				this.isStampEnabled = status
			},
			// 处理签章点击
			handleStampClick() {
				console.log('签章区域被点击')
				// 这里可以调用签章逻辑
			},
			handleDateRangeChange(e) {
				// 类型验证（避免小程序端数据类型不一致）
				if (Array.isArray(e)) {
					this.orderList.checkStartTime = this.formatDate(e[0])
					this.orderList.checkEndTime = this.formatDate(e[1])
				} else if (e?.detail?.value) { // 兼容微信小程序事件对象
					const [start, end] = e.detail.value
					this.orderList.checkStartTime = this.formatDate(start)
					this.orderList.checkEndTime = this.formatDate(end)
				}

				console.log('起始时间:', this.orderList.checkStartTime)
				console.log('结束时间:', this.orderList.checkEndTime)
			},
			formatDate(timestamp) {
				// 时间戳转日期字符串（示例格式：2025-03-25）
				return new Date(timestamp).toISOString().split('T')[0]
			},
			// 打开日期选择器
			openDatePicker() {
				this.$refs.datePopup.open();
			},
			// 日期变化暂存
			handleDateChange(e) {
				this.tempDate = e ? new Date(e) : null;
			}, // 弹窗确认
			// 修改handleDialogConfirm方法
			handleDialogConfirm() {
				if (this.tempDate) {
					const year = this.tempDate.getFullYear();
					const month = (this.tempDate.getMonth() + 1).toString().padStart(2, '0');
					const day = this.tempDate.getDate().toString().padStart(2, '0');
					const formattedDate = `${year}-${month}-${day}`;
					this.orderList.approverPersonDate = formattedDate;

				}

				this.$refs.datePopup.close();
			}, //获取字典值
			async getMedicalDict(type) {
				try {
					const res = await getMedicalDict(type)

					// 增加响应状态判断
					if (res.code === 0) {
						switch (type) {
							case 'word_address':
								this.word_address = res.data[0].remark
								break;
							default:
								return;
						}
					} else {
						throw new Error(res?.data?.msg || '接口返回异常')
					}

				} catch (error) {
					uni.showToast({
						title: error.message || '获取分类失败',
						icon: 'none',
						duration: 2000
					})
				}
			}
		}
	}
</script>

<style>
	.page {
		background-color: #e9f1fe;
		padding: 10px;
	}


	/* 虚线容器 */
	.dashed-box {
		width: 100%;
		margin: 24rpx auto;
		padding: 12rpx;
		border: 2rpx dashed #333;
		border-radius: 10rpx;
		background: #fff;
		position: relative;

		&+.dashed-box {
			margin-top: 28rpx;
		}


	}

	/* 容器改为垂直排列 */
	.container {
		width: 100%;
		display: flex;
		flex-direction: column;
		/* 关键改动：垂直排列 */
		padding: 20px 0;
	}

	/* custom-title样式改造 */
	.custom-title {
		width: 90%;
		/* 控制内容区域宽度 */
		max-width: 650rpx;
		/* 最大宽度限制 */
		margin: 20rpx 0;
		display: flex;
		justify-content: center;
		/* 水平居中 */
	}

	.content-wrapper {
		width: 100%;
		display: flex;
		align-items: center;
	}

	.label-text {
		width: 200rpx;
		/* 固定标签宽度 */
		text-align: right;
		padding-right: 20rpx;
		font-size: 18rpx;
		color: #666;
	}

	.label-text-sign {
		width: 200rpx;
		/* 固定标签宽度 */
		text-align: right;
		padding-right: 20rpx;
		padding-top: 20px;
		font-size: 18rpx;
		color: #666;
	}

	/* 带下划线的输入框样式 */
	.underline-input {
		flex: 1;
		height: 40rpx;
		border: none;
		border-bottom: 1rpx solid #000000;
		/* 底部边框作为下划线 */
		padding: 0 20rpx;
		font-size: 18rpx;
		transition: border-color 0.3s;
	}

	.underline-input:focus {
		border-bottom-color: #007AFF;
		/* 聚焦时高亮 */
		outline: none;
	}

	/* 签名区域下划线 */
	.underline-sign {
		flex: 1;
		border-bottom: 1rpx solid #000000;
		padding-bottom: 10rpx;
		/* 增加签名区域与下划线的间距 */
	}

	.custom-dateText {
		display: flex;
		margin: 20px;
		justify-content: flex-end;
		/* 子元素居左 */
	}

	.custom-text3 {
		border-bottom: 1px solid #000;
		padding-bottom: 2px;
		padding-left: 10px;
		color: #0055ff;
		font-size: 16px;

		font-weight: bold;
		padding-right: 10px;
		margin-left: 4px;
		margin-right: 4px;
	}

	/* 深度样式穿透 */
	:deep(.signature-canvas) {
		background: #f8f8f8 !important;
		border-radius: 6px;
	}

	/* 弹窗样式调整 */
	:deep(.uni-popup-dialog) {
		border-radius: 12px !important;
		padding: 20px !important;
	}

	:deep(.uni-datetime-picker) {
		margin: 15px 0;
	}


	/* 新增评价容器样式 */
	.evaluation-container {
		display: flex;
		flex-direction: column;
		gap: 32rpx;
	}

	/* 调整问题与选项间距 */
	.evaluation-item {
		display: flex;
		flex-direction: column;
		gap: 16rpx;
	}

	/* 新增评价容器样式 */
	.evaluation-container {
		display: flex;
		flex-direction: column;
		gap: 32rpx;
	}

	/* 调整问题与选项间距 */
	.evaluation-item {
		display: flex;
		flex-direction: column;
		gap: 16rpx;
	}

	/* 添加点击样式 */
	.clickable-cell {
		color: #007AFF;
		text-align: center;
		text-decoration: underline;
		cursor: pointer;
	}

	.button-container {
		display: flex;
		background-color: #ffffff;
		width: 100%;
		padding: 10px;
		flex-direction: column;



	}

	.centered-input {
		width: 100%;
		text-align: center;
		height: 80rpx;
		line-height: 80rpx;
		/* 保持与高度一致 */
		font-size: 16rpx;
		border-radius: 12rpx;
	}

	.button-save {
		margin-bottom: 10px;
	}
</style>